package com.hhs.storage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhs.storage.bean.*;
import com.hhs.storage.config.InitSystemParamRunner;
import com.hhs.storage.dao.TypeDicDao;
import com.hhs.storage.service.BaseDepartmentService;
import com.hhs.storage.service.BasePermissionService;
import com.hhs.storage.service.BusinessOrderService;
import com.hhs.storage.service.TypeDicService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhs.storage.util.StringUtil;
import com.hhs.storage.util.SysUtil;
import org.apache.commons.collections.list.TreeList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hhs
 * @since 2022-12-08
 */
@Service
@Transactional
public class TypeDicServiceImpl extends ServiceImpl<TypeDicDao, TypeDic> implements TypeDicService {
    @Autowired
    private InitSystemParamRunner initSystemParamRunner;
    @Autowired
    private ContractServiceImpl contractService;
    @Resource
    private HttpServletRequest request;
    @Resource
    BusinessOrderService businessOrderService;
    @Resource
    BaseDepartmentService baseDepartmentService;
    @Resource
    BasePermissionService basePermissionService;
   @Autowired
    TypeDicService typeDicService;
    @Override
    public Map<String, Object> getAll(String keyWord,String typeId) {
        List<TypeDic> list=new ArrayList<>();
        if (SysUtil.KEY_CONTRACT_TYPE.equals(keyWord)){
            list=SysUtil.CONTRACT_TYPE_LIST;
        }else if (SysUtil.KEY_MODEL_TYPE.equals(keyWord)){
            if(StringUtils.isEmpty(typeId) ){
                return ResponseInfo.error("参数错误");
            }
            //合同型号必须根据合同类型去过滤
            List<TypeDic> temp=SysUtil.MODEL_TYPE_LIST;
            list=new ArrayList<>();
            for (int i = 0; i <temp.size() ; i++) {
                TypeDic typeDic=temp.get(i);
                if (typeDic.getTypeId().equals(typeId)){
                    list.add(typeDic);
                }
            }
        }else if (SysUtil.KEY_PAY_TYPE.equals(keyWord)){
            list=SysUtil.PAY_TYPE_LIST;
        }else if (SysUtil.KEY_PAY_WAY.equals(keyWord)){
            list=SysUtil.PAY_WAY_LIST;
        }else if (SysUtil.KEY_PLAN_YWTYPE.equals(keyWord)){
            list=SysUtil.PLAN_YWTYPE_LIST;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("rows", list);
        map.put("code", 1);
        return map;
    }

    @Override
    public Map<String, Object> addOrUpdate(TypeDic typeDic) {
        if(StringUtils.isEmpty(typeDic.getKeyWord())){
            return ResponseInfo.error("参数错误");
        }

        //新增
        if (StringUtils.isEmpty(typeDic.getId())) {
            QueryWrapper<TypeDic> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("name", typeDic.getName());
            queryWrapper.eq("key_word", typeDic.getKeyWord());
            if(StringUtils.hasLength(typeDic.getDepartId())){
                queryWrapper.eq("depart_id",typeDic.getDepartId());
            }
            if (StringUtils.hasLength(typeDic.getTypeId())){
                queryWrapper.eq("type_id", typeDic.getTypeId());
            }
            List<TypeDic> tempList = this.list(queryWrapper);
            typeDic.setCreateTime(LocalDateTime.now());
            typeDic.setId(SysUtil.UUID());
            if (tempList.size() > 0) {
                return ResponseInfo.error("名称已存在，请重新输入");
            }
            this.save(typeDic);
        } else {//修改
            QueryWrapper<TypeDic> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("key_word",typeDic.getKeyWord());
            queryWrapper.eq("name",typeDic.getName());
            if(StringUtils.hasLength(typeDic.getDepartId())){
                queryWrapper.eq("depart_id",typeDic.getDepartId());
            }
            queryWrapper.ne("id",typeDic.getId());
            int t=this.count(queryWrapper);
            if (t>0){
                return ResponseInfo.error("名称已存在，请重新输入");
            }
            this.updateById(typeDic);
        }
        initSystemParamRunner.getTypeDic();//获取所有类型
        return ResponseInfo.success(null);
    }

    @Override
    public Map dele(String id) {
        if(!StringUtils.hasLength(id)){
            return ResponseInfo.error("参数错误");
        }
        QueryWrapper<TypeDic> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("pid",id);//删除子集
        this.remove(queryWrapper);
        this.removeById(id);
        initSystemParamRunner.getTypeDic();//重新获取
        return ResponseInfo.success(null);
    }
    public Map<String, Object> query(TypeDic typeDic,InputParam inputParam) {
        if(!StringUtils.hasLength(typeDic.getKeyWord())){
            return ResponseInfo.error("参数错误");
        }

        QueryWrapper ew = new QueryWrapper<TypeDic>();
        ew.eq("key_word",typeDic.getKeyWord());

//        判断是否有传入departId
        if (StringUtils.hasLength(typeDic.getDepartId())){
            Map<String, Object> userDepartInfo = baseDepartmentService.getDepartDataByLoginUser(inputParam);//获取当前用户所在部门与子部门
            List<BaseDepartment> mydeparts=(List<BaseDepartment>)userDepartInfo.get("userDepartment");
            List<String> d2=new ArrayList<>();
            if(mydeparts==null|| mydeparts.isEmpty()){
                return ResponseInfo.error("该用户没有分配部门");
            }
            getDepartId(mydeparts,d2);
            boolean isMysub=false;
            for (String bd : d2) {
                if(bd.equals(typeDic.getDepartId())){
                    isMysub=true;
                    break;
                }
            }
            if(isMysub||basePermissionService.hasPermission(SysUtil.getLoginUserId(request),"ywzsck")){
                List<BaseDepartment> baseDepartments = baseDepartmentService.getChildDeparts(typeDic.getDepartId());//所有子部门
                List list1 = new ArrayList();
                list1.add(typeDic.getDepartId());
                for (BaseDepartment bd :
                        baseDepartments) {
                    list1.add(bd.getId());
                }
                ew.in("depart_id",list1);
            }else{
                ew.isNull("id");
            }
        }else {
            //只能看登录者所在部门以及其下级部门
            Map<String, Object> userDepartInfo = baseDepartmentService.getDepartDataByLoginUser(inputParam);//获取当前用户所在部门
            List<BaseDepartment> baseDepartments=(List<BaseDepartment>)userDepartInfo.get("userDepartment");
            List myAndSub=new ArrayList();
            if(baseDepartments.isEmpty()){
                return ResponseInfo.error("该用户没有分配部门");
            }
            getDepartId(baseDepartments,myAndSub);
            ew.in("depart_id",myAndSub);
        }
        if(StringUtils.hasLength(typeDic.getUpdown())){
            ew.eq("updown",typeDic.getUpdown());
        }
        if(StringUtils.hasLength(typeDic.getName())){
            ew.like("name",typeDic.getName());
        }


        //查询状态可用的
        ew.eq("state",1);
        ew.orderByDesc("create_time");

        Page<TypeDic> result = this.page(new Page<TypeDic>(
                inputParam.getPage(),
                inputParam.getSize()),ew);
        //-------------------------add by yj start-------------------------------//
        List<TypeDic> list =(List<TypeDic>) this.list(ew);
        //判断部门id
        List<TypeDic> rows = result.getRecords();
        int t0=0;
        int t1=0;
        int t2=0;
        for (TypeDic type :
                list) {
            if("0".equals(type.getUpdown())){
                t0+=1;
            }
            if("1".equals(type.getUpdown())){
                t1+=1;
            }
            if("2".equals(type.getUpdown())){
                t2+=1;
            }
        }
        //厂家，中间，下家
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("rows", rows);
        map.put("t0",t0);
        map.put("t1",t1);
        map.put("t2",t2);
        //-------------------------add by yj end-------------------------------//
        map.put("total",result.getTotal());
        map.put("code", 1);
        return map;
    }
    public List<TypeDic> getDepartId(List<BaseDepartment> list,List strList){
        //遍历树  获取id数组
        for (BaseDepartment baseDepartment : list) {
            strList.add(baseDepartment.getId()); // 遍历项目满足条件后的操作
            if (baseDepartment.getChildren().size()>0) {
                //存在子节点就递归
                getDepartId(baseDepartment.getChildren(), strList);
            }
        }
        return strList;

    }
    public List<TypeDic> getUpDown(List<BaseDepartment> list,List strList ,TypeDic typeDic){
        //遍历树  获取id数组
        for (BaseDepartment baseDepartment : list) {
            strList.add(baseDepartment.getId()); // 遍历项目满足条件后的操作
            if (baseDepartment.getChildren().size()>0) {
                //存在子节点就递归
                getDepartId(baseDepartment.getChildren(), strList);
            }
        }
        return strList;

    }
    public List<TypeDic> getNameOrupDown(List<TypeDic> list,TypeDic typeDic){
        if (StringUtils.hasLength(typeDic.getName())){
            System.out.println(2);
            String selectName = typeDic.getName();
            Iterator<TypeDic> iterator = list.iterator();

            while(iterator.hasNext()){
                TypeDic newtypeDic = iterator.next();
                if(!newtypeDic.getName().contains(selectName)){
                    List<TypeDic> childrenList = newtypeDic.getSub();
                    if(!CollectionUtils.isEmpty(childrenList)){
                        getNameOrupDown(childrenList, typeDic);
                    }
                    if(CollectionUtils.isEmpty(childrenList)){
                        iterator.remove();
                    }
                }
            }
        }else if (StringUtils.hasLength(typeDic.getUpdown())){

            QueryWrapper<TypeDic>  qw= new QueryWrapper<>();
            if (!list.isEmpty() && list.stream().anyMatch(item -> item.getUpdown().equals("1"))){
                qw.eq("updown", 1);

            }
            List<TypeDic> updownList = this.list(qw);
            System.out.println("updown"+updownList);
            return updownList;


//            Iterator<TypeDic> iterator = list.iterator();
//            while(iterator.hasNext()){
//                TypeDic newtypeDic = iterator.next();
//                if(!newtypeDic.getUpdown().contains(selectName)){
//                    List<TypeDic> childrenList = newtypeDic.getSub();
//                    if(!CollectionUtils.isEmpty(childrenList)){
//                        getNameOrupDown(childrenList, typeDic);
//                    }
//                    if(CollectionUtils.isEmpty(childrenList)){
//                        iterator.remove();
//                    }
//                }
//            }
        }
        return null;
    }


    @Override
    public Map<String, Object> getAllFromDb(TypeDic typeDic,InputParam inputParam) {
        if(!StringUtils.hasLength(typeDic.getKeyWord())){
            return ResponseInfo.error("参数错误");
        }
        QueryWrapper ew = new QueryWrapper<TypeDic>();
        ew.eq("key_word",typeDic.getKeyWord());

        if(StringUtils.hasLength(typeDic.getDepartId())){
            ew.eq("depart_id",typeDic.getDepartId());
        }
        //查询姓名
        if(StringUtils.hasLength(typeDic.getName())){
            ew.like("name",typeDic.getName());
        }
        String loginUserId=SysUtil.getLoginUserId(request);
        Boolean hasPermission = basePermissionService.hasPermission(loginUserId, "ywzsck");
        if(!hasPermission){
            List<BaseDepartment> departments = baseDepartmentService.findByUserId(loginUserId);
            List<String> array=new ArrayList<>();
            for (BaseDepartment bp :
                    departments) {
                array.add(bp.getId());
            }
            String s = StringUtil.toCommaStringSql(array);
            ew.inSql("depart_id","("+s+")");
        }
        //判断pid是否为空
//        ew.isNull("pid");
        //查询状态可用的
        ew.eq("state",1);
        ew.orderByDesc("create_time");
        Page<TypeDic> result = this.page(new Page<TypeDic>(
                inputParam.getPage(),
                inputParam.getSize()),ew);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("rows", result.getRecords());
        map.put("total",result.getTotal());
        map.put("code", 1);
        return map;
    }
    @Override
    public Map<String, Object> getAllFromDb2(TypeDic typeDic,InputParam inputParam)  {
            if(!StringUtils.hasLength(typeDic.getKeyWord())){
                return ResponseInfo.error("参数错误");
            }

            QueryWrapper ew = new QueryWrapper<TypeDic>();
            ew.eq("key_word",typeDic.getKeyWord());
            if(StringUtils.hasLength(typeDic.getDepartId())){
                ew.eq("depart_id",typeDic.getDepartId());//
            }
            if(StringUtils.hasLength(typeDic.getId())){
                ew.eq("id",typeDic.getId());//
            }else{
                ew.isNull("pid");
            }

            //查询状态可用的
            ew.eq("state",1);
            ew.orderByDesc("create_time");
            Page<TypeDic> result = this.page(new Page<TypeDic>(
                    inputParam.getPage(),
                    inputParam.getSize()),ew);
            getSub(result.getRecords(),typeDic);
            //判断部门id
            List<TypeDic> rows = result.getRecords();

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("rows", getNameOrupDown(rows,typeDic));
            map.put("code", 1);
            return map;
        }

    public List<TypeDic> getSub(List<TypeDic> list,TypeDic typeDic) {
        for (int i = 0; i < list.size(); i++) {
            //获取该父类下的所有子类
            QueryWrapper queryWrapper = new QueryWrapper<TypeDic>();

            if(StringUtils.hasLength(list.get(i).getId())){
                queryWrapper.eq("pid",list.get(i).getId());
            }
            List<TypeDic> subList = this.list(queryWrapper);
            //修改
            list.get(i).setSub(subList);
            //判断是否还有下级子类
            QueryWrapper qw = new QueryWrapper<TypeDic>();
            qw.select("pid");
            qw.isNotNull("pid");

            List<TypeDic> tempList = this.list(qw);
            for (int j = 0; j < tempList.size(); j++) {
                if (list.get(i).getId().equals(tempList.get(j).getPid())){
                    getSub(subList,typeDic);
                }
            }
        }

        return list;
    }
    @Override
    public Map<String, Object> getUpDown(TypeDic typeDic,InputParam inputParam) {
        QueryWrapper ew = new QueryWrapper<TypeDic>();
        List<TypeDic> updownList = this.list(ew);
        List list = new ArrayList();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", 0);
        map.put("label", updownList.get(0).getUpName());
        map.put("value", 0);
        list.add(map);
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("id", 1);
        map1.put("label", updownList.get(0).getFlatName());
        map1.put("value", 1);
        list.add(map1);
        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("id", 2);
        map2.put("label", updownList.get(0).getDownName());
        map2.put("value", 2);
        list.add(map2);
        Map<String, Object> map3 = new HashMap<String, Object>();
        map3.put("code", 1);
        map3.put("data", list);
        return map3;
        }

    @Override
    public Map<String, Object> editUpDown(TypeDic typeDic,InputParam inputParam) {
        UpdateWrapper<TypeDic> qw=new UpdateWrapper<>();
        if((!StringUtils.hasLength(typeDic.getUpName()))&&(!StringUtils.hasLength(typeDic.getDownName()))&&(!StringUtils.hasLength(typeDic.getFlatName()))){
            return ResponseInfo.error("参数错误");
        }
        if (StringUtils.hasLength(typeDic.getUpName())){
            qw.set("up_name",typeDic.getUpName());
        }
        if (StringUtils.hasLength(typeDic.getDownName())){
            qw.set("down_name",typeDic.getDownName());
        }
        if (StringUtils.hasLength(typeDic.getFlatName())){
            qw.set("flat_name",typeDic.getFlatName());
        }
        typeDicService.update(null,qw);
        return ResponseInfo.success("编辑成功");
    }


//    @Override
//    public Map<String, Object> query(TypeDic typeDic,InputParam inputParam) {
//        if(!StringUtils.hasLength(typeDic.getKeyWord())){
//            return ResponseInfo.error("参数错误");
//        }
//        QueryWrapper ew = new QueryWrapper<TypeDic>();
//        ew.eq("key_word",typeDic.getKeyWord());
//        if(StringUtils.hasLength(typeDic.getId())){
//            ew.eq("id",typeDic.getId());
//        }else{
//            ew.isNull("pid");
//        }
//        //查询状态可用的
//        ew.eq("state",1);
//        ew.orderByDesc("create_time");
//        Page<TypeDic> result = this.page(new Page<TypeDic>(
//                inputParam.getPage(),
//                inputParam.getSize()),ew);
//        getSub(result.getRecords(),typeDic);
//        List<TypeDic> rows = result.getRecords();
//        //查询姓名时 去除subList为空的
//        if(StringUtils.hasLength(typeDic.getName())){
//            List<TypeDic> newRows = new ArrayList<>();
//            for (int i = 0; i < rows.size(); i++) {
//                if (rows.get(i).getSub().size()>0||rows.get(i).getName().indexOf(typeDic.getName())!=-1){
//                    newRows.add(rows.get(i));
//                }
//            }
//            rows=newRows;
//        }
//
//        Map<String, Object> map = new HashMap<String, Object>();
////        System.out.println(rows.get(0).getSub());
//        map.put("rows", rows.get(0).getSub());
//        map.put("code", 1);
//        return map;
//    }
    @Override
    public Map deleForBussiness(String id) {
        if(StringUtils.isEmpty(id)){
            return ResponseInfo.error("参数错误");
        }
        QueryWrapper<BusinessOrder> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("start_place",id);//不是合同类型
        queryWrapper.or().eq("end_place",id);//不是合同型号
        int total=businessOrderService.count(queryWrapper);
        if (total>0){
            return ResponseInfo.error("数据存在相关业务，无法删除");
        }
        this.removeById(id);
        return ResponseInfo.success(null);
    }

    @Override
    public Map allByKey(String keyWord) {
        if(StringUtils.isEmpty(keyWord)){
            return ResponseInfo.error("参数错误");
        }
        QueryWrapper ew = new QueryWrapper<TypeDic>();
        ew.eq("key_word",keyWord);
        ew.eq("state",1);
        ew.orderByDesc("create_time");
        List list = this.list(ew);
        return ResponseInfo.success(list);
    }

    @Override
    public Region formatRegion(String id) {
        if(StringUtils.isEmpty(id)){
            return null;
        }
        Region region = new Region();
        TypeDic typeDic = getById(id);
        if(typeDic==null) {return null;}
        region.setId(typeDic.getId());
        region.setName(typeDic.getName());
        region.setMername(typeDic.getName());

        return region;
    }

    @Override
    public Map<String, Object> changeState(TypeDic typeDic) {
        this.updateById(typeDic);
        return ResponseInfo.success(null);
    }

    @Override
    public Map<String, Object> getByDepart(TypeDic typeDic) {
        String userId = SysUtil.getLoginUserId(request);
        List<BaseDepartment> departmentList = baseDepartmentService.findByUserId(userId);
        Set<String> departIdSet = new HashSet<>();
        for (BaseDepartment department : departmentList) {
            departIdSet.add(department.getId());
        }
        QueryWrapper<TypeDic> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("key_word",typeDic.getKeyWord());
        queryWrapper1.in("depart_id", departIdSet);
        List list = this.list(queryWrapper1);
        return ResponseInfo.success(list);
    }
}
